package org.leon.builder;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.leon.pojo.Configuration;
import org.leon.pojo.MapperStatement;
import org.leon.pojo.SqlTypeEnum;

import java.io.InputStream;
import java.util.List;

/**
 * Created by leon.L on 2019/12/24.
 * Desc :
 */
public class XmlMapperBuilder {

    private Configuration configuration;

    public XmlMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {

        Document document = new SAXReader().read(inputStream);
        Element rootEle = document.getRootElement();

        String namespace = rootEle.attributeValue("namespace");

        List<Element> childElements = rootEle.elements();

        // 解析 mapper.xml 文件中的 sql 标签并封装成 MapperStatement 对象，放入到 Configuration 的 sqlMapper 集合中
        for (Element ele : childElements) {
            MapperStatement ms = new MapperStatement();

            ms.setId( ele.attributeValue("id") );
            ms.setParamterType( ele.attributeValue("paramterType") );
            ms.setSql( ele.getTextTrim() );
            ms.setResultType( ele.attributeValue("resultType") );

            // 标记识别每条sql的操作类型，是增删改查的哪一种
            String eleName = ele.getName();
            SqlTypeEnum sqlType = SqlTypeEnum.getType(eleName);
            if (sqlType == null) {
                throw new RuntimeException(String.format("Unsupported operation [%s], only support select, update, insert, delete.", eleName));
            }else {
                ms.setSqlType(sqlType);
            }

            String statementId = namespace.concat(".").concat(ms.getId());
            configuration.getSqlMapper().put(statementId, ms);
        }

    }
}
